package top.itpath.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import top.itpath.admin.entity.SysMenu;
import top.itpath.admin.entity.SysRoleMenu;
import top.itpath.admin.mapper.SysMenuMapper;
import top.itpath.admin.mapper.SysRoleMenuMapper;
import top.itpath.admin.service.ISysRoleMenuService;

import javax.transaction.Transactional;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zhaomengru
 * create by  2023/10/11 - 13:48
 */
@Service
@RequiredArgsConstructor
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {

    private final SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenu> listRoleMenu(Collection<Long> roleId) {
        if (CollectionUtil.isEmpty(roleId)) {
            return List.of();
        }
        List<SysRoleMenu> sysRoleMenus = CollectionUtil.emptyIfNull(this.lambdaQuery().in(SysRoleMenu::getRoleId, roleId).list());
        Set<Long> menuIds = sysRoleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toSet());
        if (CollectionUtil.isEmpty(menuIds)) {
            return List.of();
        }
        return sysMenuMapper.selectBatchIds(menuIds);
    }

    @Override
    public Set<String> listRolePermissions(Collection<Long> roleId) {
        if (CollectionUtil.isEmpty(roleId)) {
            return Collections.emptySet();
        }
        List<SysRoleMenu> sysRoleMenus = CollectionUtil.emptyIfNull(this.lambdaQuery()
                .in(SysRoleMenu::getRoleId, roleId)
                .list());
        Set<Long> menuIds = sysRoleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toSet());
        if (CollectionUtil.isEmpty(menuIds)) {
            return Collections.emptySet();
        }
        return CollectionUtil.emptyIfNull(sysMenuMapper.selectBatchIds(menuIds))
                .stream()
                .filter(item -> SysMenu.MenuType.BUTTON == item.getType())
                .map(SysMenu::getPermission)
                .collect(Collectors.toSet());
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public void setPermission(Long roleId, List<Long> menuIds) {
        if (CollectionUtil.isEmpty(menuIds)) {
            return;
        }
        this.lambdaUpdate().eq(SysRoleMenu::getRoleId, roleId).remove();
        List<SysRoleMenu> sysRoleMenus = menuIds.stream().map(item -> {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenu.setMenuId(item);
            return sysRoleMenu;
        }).collect(Collectors.toList());
        this.saveBatch(sysRoleMenus);
    }
}
